/**
 * 
 */
package org.lbspoc.springboot1.boot.controller;

import java.util.List;

import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.lbspoc.springboot1.boot.model.LbsInfo;
import org.lbspoc.springboot1.boot.model.LbsReq;
import org.lbspoc.springboot1.boot.model.SimpleMessage;
import org.lbspoc.springboot1.boot.service.MongoDbService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;



/**
 * @author chenxianpeng
 *
 */
@RestController
@EnableAutoConfiguration
public class LbsPocController {
	private static Logger logger = Logger.getLogger(LbsPocController.class);
	
	@Autowired
	private MongoDbService mongoDb;

	/**
	 * 
	 */
	public LbsPocController() {
		// TODO Auto-generated constructor stub
	}

	@RequestMapping(value="/lbsInfo", method=RequestMethod.POST)
	public SimpleMessage upsert(@RequestBody @Valid LbsInfo info) {
		LbsInfo inDb = mongoDb.findByUserId(info.getUser_id());
		if(inDb == null) {
			mongoDb.insert(info);
		} else {
			inDb.setLongitude(info.getLongitude());
			inDb.setLatitude(info.getLatitude());
			inDb.setLast_updated_ts(info.getLast_updated_ts());
			mongoDb.update(inDb);
		}
		return SimpleMessage.createGoodMessage();
	}
	
	@RequestMapping(value="/lbsInfo/{uid}", method=RequestMethod.DELETE)
	public SimpleMessage delete(@PathVariable("uid") long uid) {
		LbsInfo inDb = mongoDb.findByUserId(uid);
		SimpleMessage sm = new SimpleMessage();
		if(inDb == null) {
			sm.setCode(SimpleMessage.GOOD);
			sm.setMessage("user not exist");
		} else {
			mongoDb.deleteById(uid);
			sm.setCode(SimpleMessage.GOOD);
			sm.setMessage("deleted");
		}
		return sm;
	}
	
	@RequestMapping(value="/lbsInfoSearch", method=RequestMethod.POST)
	public List<LbsInfo> search(@RequestBody @Valid LbsReq req) {
		logger.info("start to search...");
		List<LbsInfo> ret =  mongoDb.search(req);
		logger.info("end");
		return ret;
	}
}
